<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">

<head th:replace="_fregments :: head(~{::title})">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>链接管理</title>
    <!-- Bootstrap -->
    <link rel="stylesheet" href="../../static/lib/bootstrap-3.4.1/css/bootstrap.min.css">
    <!-- bootstrap-select -->
    <link href="../../static/lib/bootstrap-select/bootstrap-select.css" rel="stylesheet">
    <link rel="stylesheet" href="../../static/css/my.css">
    <!-- 动画 -->
    <link rel="stylesheet" href="../../static/css/animate.css">
    <!-- bootstrap-select -->
    <link href="../../static/lib/bootstrap-select/bootstrap-select.css" rel="stylesheet">
    <!-- bootstrap-bootstrapValidator-->
    <link rel="stylesheet" href="../../static/lib/bootstrapValidator/bootstrapValidator.min.css">
</head>

<body>
<nav th:replace="_fregments :: menu(4)" class="navbar navbar-default navbar-fixed-top m-padding">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">
                <img alt="Brand" src="../../static/favicon.ico" style="width: 24px;">
            </a>
            <p class="navbar-text navbar-default"><a href="#" class="navbar-link m-a-none"><b>后台管理</b></a></p>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li><a href="index.html"><span class="glyphicon glyphicon-home">&nbsp;</span>首页</a></li>
                <li><a href="navigation.html"><span class="glyphicon glyphicon-tasks">&nbsp;</span>导航管理</a></li>
                <li><a href="tag.html"><span class="glyphicon glyphicon-tag">&nbsp;</span>标签管理</a></li>
                <li class="active"><a href="link.html"><span class="glyphicon glyphicon-link">&nbsp;</span>链接管理</a>
                </li>
                <li role="presentation" class="disabled"><a href="#"><span
                        class="glyphicon glyphicon-bookmark">&nbsp;</span>书签管理</a></li>
            </ul>

            <ul class="nav navbar-nav navbar-right">
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
                       aria-expanded="false">
                        <img class="m-avatar img-circle" src="../../static/images/me.jpg">
                        挚夕
                        <span class="caret"></span>
                    </a>
                    <ul class="dropdown-menu dropdown-menu-left">
                        <li><a href="#"><span class="glyphicon glyphicon-th">&nbsp;</span>个人主页</a></li>
                        <li role="separator" class="divider"></li>
                        <li><a href="#"><span class="glyphicon glyphicon-log-out">&nbsp;</span>登出</a></li>
                    </ul>
                </li>
            </ul>

            <form class="navbar-form navbar-right">
                <div class="form-group">
                    <input type="text" class="form-control" placeholder="搜索" style="width: 300px;">
                </div>
                <button type="submit" class="btn btn-default">
                    <a class="glyphicon glyphicon-search m-none"></a>
                </button>
            </form>
        </div><!-- /.navbar-collapse -->
    </div><!-- /.container-fluid -->
</nav>


<!-- 新增/修改链接模态窗口 -->
<div class="modal fade" id="addLinkModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">添加链接</h4>
            </div>
            <div class="modal-body">
                <form>
                    <input type="hidden" id="input-modal-hidden">
                    <div class="form-group">
                        <label for="input-title">链接标题</label>
                        <input type="text" class="form-control" name="inputTitle" id="input-title"
                               placeholder="链接标题">
                    </div>
                    <div class="form-group">
                        <label for="input-brief">链接简述</label>
                        <input type="text" class="form-control" name="inputBrief" id="input-brief"
                               placeholder="链接简述">
                    </div>
                    <div class="form-group">
                        <label for="textarea-detail">链接详情</label>
                        <textarea class="form-control" rows="10" name="textareaDetail" id="textarea-detail"
                                  placeholder="链接详情"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="input-url">链接网址</label>
                        <input type="text" class="form-control" name="inputUrl" id="input-url" placeholder="链接网址">
                    </div>
                    <div class="form-group">
                        <label for="select-modal-first">一级导航</label>
                        <select id="select-modal-first" name="select-modal-first" class="form-control selectpicker"
                                data-live-search="true" required autofocus>
                            <option th:each="nav : ${firstNavigation}" th:text="${nav.name}" th:value="${nav.id}">
                                常用推荐
                            </option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="select-modal-second">二级导航</label>
                        <select id="select-modal-second" data-live-search="true"
                                class="form-control selectpicker" required autofocus>
                            <option th:each="nav : ${secondNavigation}" th:value="${nav.id}" th:text="${nav.name}">
                                短视频
                            </option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="select-modal-tag">标签</label>
                        <select id="select-modal-tag" class="form-control selectpicker" multiple
                                data-live-search="true" data-selected-text-format="count > 3">
                            <option th:each="tag, it : ${tags}" th:value="${tag.id}" th:text="${tag.name}">短视频
                            </option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="input-url">优先级（数值越大越靠前显示）</label>
                        <select class="form-control" id="select-modal-priority" required autofocus>
                            <option value="1">1</option>
                            <option value="2">2</option>
                            <option value="3">3</option>
                            <option value="4">4</option>
                            <option value="5">5</option>
                            <option value="6">6</option>
                            <option value="7">7</option>
                            <option value="8">8</option>
                            <option value="9">9</option>
                            <option value="10">10</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="input-url">图标链接(为空时将使用默认API获取)</label>
                        <input type="text" class="form-control" name="inputIcon" id="input-icon" placeholder="图标链接">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="btn-modal-add">添加</button>
            </div>
        </div>
    </div>
</div>

<div class="m-margin-top">
    <div class="m-container">
        <div class="panel panel-default">
            <div class="panel-heading">
                <div class="panel-body">
                    <div class="row">
                        <div class="col-xs-12 col-sm-6 col-md-3 form-group">
                            <select id="first-nav-select"
                                    class="form-control form-control-placeholder m-select selectpicker"
                                    data-live-search="true">
                                <option value="-1" disabled selected hidden>一级导航</option>
                                <option th:each="nav, it : ${firstNavigation}" th:text="${nav.name}"
                                        th:value="${nav.id}">常用推荐
                                </option>
                            </select>
                        </div>
                        <div class="col-xs-12 col-sm-6 col-md-3 form-group">
                            <select id="second-nav-select"
                                    class="form-control form-control-placeholder m-select selectpicker"
                                    data-live-search="true">
                                <option value="-1" disabled selected hidden>二级导航</option>
                                <option th:each="nav, it : ${secondNavigation}" th:text="${nav.name}"
                                        th:value="${nav.id}">短视频
                                </option>
                            </select>
                        </div>
                        <div class="col-xs-12 col-sm-6 col-md-3 form-group">
                            <input placeholder="链接名称" id="input-search" class="form-control m-input">
                        </div>
                        <div class="col-xs-12 col-sm-6 col-md-3">
                            <button type="submit" class="btn btn-danger btn-sm" id="btn-clear">
                                清空
                            </button>
                            <button type="submit" class="btn btn-success btn-sm" id="btn-search">
                                <span class="glyphicon glyphicon-search m-none">&nbsp;</span>搜索
                            </button>
                            <button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#addLinkModal"
                                    data-title="新增链接" id="btn-add-link">新增
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="panel-body">
                <table class="table table-striped">
                    <thead>
                    <td>#</td>
                    <td>链接名称</td>
                    <td>简述</td>
                    <td>网址</td>
                    <td>一级菜单</td>
                    <td>二级菜单</td>
                    <td>操作</td>
                    </thead>
                    <tbody id="tbody-link">
                    <tr th:each="link,it :${linkPage.records}">
                        <td th:text="${it.count}">1</td>
                        <td th:text="${link.title}">BliBili</td>
                        <td th:text="${link.brief}">二次元网址</td>
                        <td><a th:href="${link.url}" target="_blank" th:text="${link.url}"></a></td>
                        <td th:text="${link.firstNavName}">常用推荐</td>
                        <td th:text="${link.secondNavName}">短视频</td>
                        <td>
                            <button type="button" class="btn btn-primary btn-sm" data-toggle="modal"
                                    data-target="#addLinkModal" th:data-id="${link.id}"
                                    data-title="修改链接">修改
                            </button>
                            <button type="button" class="btn btn-danger btn-sm btn-delete" th:data-id="${link.id}"
                                    th:data-name="${link.title}">删除
                            </button>
                        </td>
                    </tr>
                    </tbody>
                </table>
                <div class="m-pagination-div" id="div-pagination">
                    <nav aria-label="...">
                        <ul class="pager">
                            <li onclick="page(this)" th:data-current="${linkPage.current - 1}" class="previous"
                                th:classappend="${!linkPage.hasPrevious}? 'disabled'"><a><span
                                    aria-hidden="true">&larr;</span> 上一页</a></li>
                            <li onclick="page(this)" th:data-current="${linkPage.current + 1}" class="next"
                                th:classappend="${!linkPage.hasNext}? 'disabled'"><a>下一页 <span aria-hidden="true">&rarr;</span></a>
                            </li>
                        </ul>
                    </nav>
                </div>
            </div>
            <div class="panel-footer m-align-right">

            </div>
        </div>
    </div>
</div>

<br><br><br><br><br><br><br><br><br><br><br>
<footer th:replace="_fregments :: footer">
    <div>
        <div class="row">
            <div class="col-sm-4 col-md-4">
                <h3>挚夕导航</h3>
                <p>
                    挚夕导航最初源于本人想要做一个管理书签的系统。<br>
                    后来借鉴了一些导航网站，决定做一个网站导航。<br>
                    前端使用BootStrap。
                </p>
            </div>
            <div class="col-sm-8 col-md-8">
                占位
            </div>
        </div>
    </div>

    <div style="text-align: center;">
        Copyright 2023-now 挚夕导航 Designed by 挚夕
    </div>
</footer>

<!--/*/<th:block th:replace="_fregments :: script">/*/-->
<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery，所以必须放在前边) -->
<script src="../../static/lib/jquery-1.12.4/jquery.min.js"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="../../static/lib/bootstrap-3.4.1/js/bootstrap.min.js"></script>
<!--  bootstrap-dropdown-hover -->
<script src="../../static/lib/bootstrap-dropdown-hover.js"></script>
<!-- bootstrap-select-->
<script src="../../static/lib/bootstrap-select/bootstrap-select.js"></script>
<script src="../../static/lib/bootstrap-select/defaults-zh_CN.js"></script>
<script src="../../static/lib/toastr/toastr.min.js"></script>
<!-- bootstrap-bootstrapValidator-->
<script src="../../static/lib/bootstrapValidator/bootstrapValidator.min.js"></script>
<script src="../../static/lib/bootstrapValidator/zh_CN.js"></script>
<script>
    $(function () {
        //bootstrap-dropdown-hover
        $('.navbar [data-toggle="dropdown"]').bootstrapDropdownHover({
            // see next for specifications
        });
        //特效
        $("li").hover(function () {
            $(this).toggleClass("m-up");
        })
    })
</script>
<!--/*/</th:block>/*/-->


<script>
    //分页显示条数
    const pageSize = 10;

    //分页搜索
    function queryPage(pageNo, pageSize) {
        //收集参数
        let title = $("#input-search").val().trim();
        let firstNavId = $("#first-nav-select").val();
        let secondNavId = $("#second-nav-select").val();
        if (firstNavId === -1) firstNavId = null;
        if (secondNavId === -1) firstNavId = null;

        $.ajax({
            type: 'get',
            url: '[[@{/admin/link/search}]]',
            data: {
                title: title,
                firstNavId: firstNavId,
                secondNavId: secondNavId,
                pageNo: pageNo,
                pageSize: pageSize
            },
            success: function (response) {
                if (response.status == 'success') {
                    template(response.data);
                }
            },
            error: function (response) {
                toastr.error(response.responseText, "请求失败");
            }
        })
    }

    //翻页按钮事件
    function page(obj) {
        if (!$(obj).hasClass("disabled"))
            queryPage($(obj).data('current'), pageSize);
    }

    //渲染数据
    function template(pageObj) {
        // console.log(pageObj);
        //表格数据
        let htmlStr = '';
        $.each(pageObj.records, function (index, obj) {
            htmlStr += "<tr>";
            htmlStr += "<td>" + (index + 1) + "</td>";
            htmlStr += "<td>" + obj.title + "</td>";
            htmlStr += "<td>" + obj.brief + "</td>";
            htmlStr += "<td><a target=\"_blank\" href='" + obj.url + "'> " + obj.url + "</a></td>";
            htmlStr += "<td>" + obj.firstNavName + "</td>";
            htmlStr += "<td>" + obj.secondNavName + "</td>";
            htmlStr += "<td>";
            htmlStr += "<button type=\"button\" class=\"btn btn-primary btn-sm\" data-toggle=\"modal\" data-target=\"#addLinkModal\" data-title=\"修改链接\" data-id='" + obj.id +
                "'>修改</button>&nbsp;"
            htmlStr += "<button type=\"button\" class=\"btn btn-danger btn-sm btn-delete\" data-id='" + obj.id + "' data-name='" + obj.title + "'>删除</button>";
            htmlStr += "</td>"
            htmlStr += "<tr>";
        });
        $("#tbody-link").html(htmlStr);
        //分页条
        htmlStr = '';
        htmlStr += "<nav aria-label=\"...\">";
        htmlStr += "<ul class=\"pager\">";
        htmlStr += "<li onclick=\"page(this)\" data-current='" + (pageObj.current - 1) + "' class=\"previous " + (pageObj.current <= 1 ? 'disabled' : '') + "\"><a>" + "<span aria-hidden=\"true\">&larr;</span>上一页</a></li>";
        htmlStr += "<li onclick=\"page(this)\" data-current='" + (pageObj.current + 1) + "' class=\"next " + (pageObj.current >= pageObj.pages ? 'disabled' : '') + "\"><a>下一页" + "<span aria-hidden=\"true\">&rarr;</span></a></li>";
        htmlStr += "</ul>";
        htmlStr += "</nav>";
        $("#div-pagination").html(htmlStr);
    }

    $(function () {
        //表单验证
        $('#addLinkModal').bootstrapValidator({
            excluded: [":disabled", ":hidden"], // 关键配置，表示只对于禁用域不进行验证，其他的表单元素都要验证
            message: '验证失败',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                inputTitle: {
                    message: '链接名校验失败',
                    validators: {
                        notEmpty: {
                            message: '链接名不能为空'
                        },
                        stringLength: {
                            min: 2,
                            max: 10,
                            message: '链接名必须在2到10位之间'
                        }
                    }
                },
                inputBrief: {
                    message: '链接简述校验失败',
                    validators: {
                        notEmpty: {
                            message: '链接简述不能为空'
                        },
                        stringLength: {
                            min: 2,
                            max: 20,
                            message: '链接简述长度必须在2到20位之间'
                        }
                    }
                },
                textareaDetail: {
                    message: '链接详情校验失败',
                    validators: {
                        notEmpty: {
                            message: '链接详情不能为空'
                        },
                        stringLength: {
                            max: 200,
                            message: '链接简述长度不能超过200'
                        }
                    }
                },
                inputUrl: {
                    validators: {
                        notEmpty: {
                            message: '链接网址不能为空'
                        },
                        regexp: {
                            regexp: /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/[\]@!\$&'\*\+,;=.]+$/,
                            message: '请输入合法的链接网址'
                        }
                    }
                }
                // inputIcon: {
                //     validators: {
                //         notEmpty: {
                //             message: '网站图标不能为空'
                //         }
                //     }
                // }
            }
        });

        function clearSearchInput() {
            $("#first-nav-select").selectpicker('val', -1);
            $("#second-nav-select").selectpicker('val', -1);
            $("#input-search").val("");
        }

        // 清空
        $("#btn-clear").click(function () {
            clearSearchInput();
        });

        //模态框事件
        $('#addLinkModal').on('show.bs.modal', function (event) {
            var button = $(event.relatedTarget) // Button that triggered the modal
            var title = button.data('title') // Extract info from data-*
            var id = button.data('id')
            // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
            var modal = $(this)
            modal.find('.modal-title').text(title)
            // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
            if (id) {
                //查标签数据
                modal.find('#input-modal-hidden').val(id);
                $.ajax({
                    type: "get",
                    url: "[[@{/admin/link/get}]]",
                    data: {
                        id: id
                    },
                    success: function (response) {
                        modal.find('#input-title').val(response.data.title);
                        modal.find('#input-brief').val(response.data.brief);
                        modal.find('#textarea-detail').val(response.data.detail);
                        modal.find('#input-url').val(response.data.url);
                        modal.find('#input-icon').val(response.data.icon);
                        modal.find('#select-modal-priority').val(response.data.priority);
                        $('#select-modal-first').selectpicker('val', response.data.firstNavId);
                        $('#select-modal-second').selectpicker('val', response.data.secondNavId);
                        // console.log(response.data);
                        // modal.find('#select-modal-tag').val();
                        if (response.data.tagIds == null || response.data.tagIds.length == 0) {
                            $("#select-modal-tag").selectpicker('val', -1);
                        } else {
                            // console.log(response.data.tagIds);
                            $("#select-modal-tag").selectpicker('val', response.data.tagIds);
                        }
                    }
                })
            }
        });

        //新增按钮事件
        $("#btn-add-link").click(function () {
            //清空模态框输入
            clearModalInput();
        });

        function clearModalInput() {
            //清空模态框输入
            $("#input-modal-hidden").val(null);
            $("#input-title").val('');
            $("#input-brief").val('');
            $("#textarea-detail").val('');
            $("#input-url").val('');
            $("#input-icon").val('');
            //选中第一个 导航菜单
            var firstVal = $("#select-modal-first option:first").val();
            $("#select-modal-first").selectpicker('val', firstVal);
            firstVal = $("#select-modal-second option:first").val();
            $("#select-modal-second").selectpicker('val', firstVal);
            //未选中 标签
            $("#select-modal-tag").selectpicker('val', -1);
            $("#select-modal-priority").val(1);
        }

        //新增/修改 链接
        $("#btn-modal-add").click(function () {
            var bootstrapValidator = $("#addLinkModal").data("bootstrapValidator").validate();
            if (!bootstrapValidator.isValid()) return;
            //收集参数
            var id = $("#input-modal-hidden").val();
            var title = $("#input-title").val();
            var brief = $("#input-brief").val();
            var detail = $("#textarea-detail").val();
            var url = $("#input-url").val();
            var icon = $("#input-icon").val();
            var firstNavId = $("#select-modal-first").val();
            var secondNavId = $("#select-modal-second").val();
            var priority = $("#select-modal-priority").val();
            var tagIds = null;
            if ($("#select-modal-tag").val()) {
                tagIds = $("#select-modal-tag").val().join(',')
            }

            $.ajax({
                type: id ? "put" : "post",
                url: id ? "[[@{/admin/link/update}]]" : "[[@{/admin/link/add}]]",
                data: {
                    id: id,
                    title: title,
                    brief: brief,
                    detail: detail,
                    url: url,
                    firstNavId: firstNavId,
                    secondNavId: secondNavId,
                    tagIds: tagIds,
                    icon: icon,
                    priority : priority
                },
                success: function (response) {
                    var msg = id ? '修改成功' : '新增成功';
                    if (response.status == 'success') {
                        //关闭模态框
                        $("#addLinkModal").modal('hide');
                        //清空模态框输入
                        clearModalInput();
                        toastr.success(msg, '提示');
                        //刷新列表
                        reload();
                        //重置表单
                        $('#addLinkModal').bootstrapValidator('resetForm')
                    } else {
                        toastr.error(response.data.errorMessage, '错误');
                    }
                },
                error: function (response) {
                    toastr.error(response.responseText, "请求失败");
                }
            })
        });

        //重新加载列表
        function reload() {
            //清空搜索输入
            // clearSearchInput();
            queryPage(1, pageSize);
        }

        //删除
        $("#tbody-link").on('click', '.btn-delete', function () {
            var id = $(this).data('id');
            var name = $(this).data('name');
            swal({
                title: "提示",
                text: "确认删除" + " <" + name + "> " + "吗?",
                icon: "warning",
                dangerMode: true,
                buttons: ['取消', '确认']
            }).then(function (willDelete) {
                if (willDelete) {
                    $.ajax({
                        type: 'delete',
                        url: '[[@{/admin/link/delete/}]]' + id,
                        success: function (response) {
                            if (response.status == 'success') {
                                //重新加载表格数据
                                reload();
                                swal("删除成功！", {
                                    icon: "success",
                                });
                            } else {
                                swal("删除失败:" + response.data.errorMessage, {
                                    icon: "error",
                                    buttons: "确认"
                                });
                            }
                        },
                        error: function (response) {
                            toastr.error(response.data.errorMessage, '错误');
                        }
                    })
                } else {
                    swal("操作取消", {
                        icon: "info",
                        button: "确认",
                    });
                }
            });
        });

        //搜索
        $("#btn-search").click(function () {
            queryPage(1, pageSize);
        });
    });
</script>
</body>

</html>